#include "Socket.hpp"
#include "Protocol.hpp"
#include "Common.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

void GetInput(int &x, int &y, char &op){
	std::cout<<"Please input x: ";
	std::cin>>x;
	std::cout<<"Please input y: ";
	std::cin>>y;
	std::cout<<"Please input op: ";
	std::cin>>op;
}

// ./tcpclient ip port
int main(int argc, char* argv[]){
	if(argc != 3){
		std::cerr<<"Usage: ./tcpserver port"<<std::endl;
		exit(USAGE_ERR);
	}

	std::string server_ip = argv[1];
	uint16_t port = std::stoi(argv[2]);

	// 创建套接字
	std::unique_ptr<Socket> client = std::make_unique<TcpSocket>();
	client->BuildTcpClientSocketMethod();

	// 连接服务器
	if(client->Connect(server_ip, port) < 0){
		exit(CONNECT_ERR);
	}

	// 构建并发送请求
	std::unique_ptr<Protocol> protocol = std::make_unique<Protocol>();
	std::string resp_buffer;
	while(true){
		int x, y;
		char op;
		GetInput(x, y, op);
		std::string req_str = protocol->BulidRequestString(x, y, op);
		client->Send(req_str);

		// 接收响应
		Response resp;
		bool ret = protocol->GetResponse(client, resp_buffer, resp);
		if(ret)
			resp.ShowResult();
		else{
			std::cout<<"server closed"<<std::endl;
			break;
		}	
	}
	
	client->Close();

	return 0;
}